import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import {getLanguage} from "@/lang";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_CONTROL_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout 15秒超时
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['Test'] = '123'

    // 时区偏移量
    // config.headers['TimezoneOffset'] = new Date().getTimezoneOffset();

    // 当前的对应的语言
    config.headers['Accept-Language'] = getLanguage()

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }



    // 默认请求出错弹窗提示，加上 withoutMessage 配置不提示
    if (config.withoutMessage) {
      service.responseWithoutMessage = true;
    }

    // 默认不处理 error 不等于 0的情况，加上 handleError 后, error 不等于0的情况 resolve 处理
    if (config.handleError) {
      service.handleError = true;
    }

    if (config.isNotJson) {
      service.isNotJson = true;
    }

    service.handleResponse = false
    if(config.handleResponse){
      service.handleResponse = true;
    }

    return config;
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    if(service.handleResponse){
      return response
    }
    if (response.headers['content-type'].match(/application\/json/)) {
      const res = response.data;

      if (res.error === 101) {
        Message({
          message: '登录失效',
          type: 'error',
          duration: 2 * 1000
        })
        store.commit('user/SET_ROLES', [])
        removeToken();

        /*setTimeout(() => {
          router.push({
            path: '/login?redirect='
          })
        }, 2 * 1000);*/
        return res;
      } else {

        if (service.handleError) {
          return res;
        } else {
          if (res.error !== 0) {
            console.error('请求失败：', res.message);

            // 弹窗提示
            if (!service.responseWithoutMessage) {
              Message({
                message: res.message,
                type: 'error',
                duration: 3 * 1000
              });
            } else {
              service.responseWithoutMessage = false;
            }

            res.toString = () => {
              return res.message;
            }
            return Promise.reject(res);
          } else {
            return res;
          }
        }

      }
    } else {
      if (service.isNotJson) {
        return response;
      } else {
        console.error('数据类型错误') // for debug
        // 弹窗提示
        if (!service.responseWithoutMessage) {
          Message({
            message: '服务器繁忙，请稍后再试',
            type: 'error',
            duration: 3 * 1000
          });
        } else {
          service.responseWithoutMessage = false;
        }
        throw new Error('服务器繁忙，请稍后再试');
      }
    }
  },
  error => {
    console.error('请求错误：', error) // for debug

    // 弹窗提示
    if (!service.responseWithoutMessage) {
      Message({
        message: '服务器繁忙，请稍后再试',
        type: 'error',
        duration: 3 * 1000
      });
    } else {
      service.responseWithoutMessage = false;
    }

    return Promise.reject(new Error('服务器繁忙，请稍后再试'));
  }
)

// 对 catch 信息过滤
let request = (config) => {
  return new Promise((resolve, reject) => {
    service(config)
      .then(res => {
        resolve(res);
      })
      .catch(error => {
        if (config.throwCatch) {
          reject(error);
        }
      })
  })
};

export default request
